package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.ZbType;
import com.xiaoye.qbproject.mapper.ZbTypeMapper;
import com.xiaoye.qbproject.service.ZbTypeService;
import com.xiaoye.qbproject.util.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【ZB_TYPE(装备类型)】的数据库操作Service实现
 * @createDate 2024-12-27 02:32:39
 */
@Service
public class ZbTypeServiceImpl extends ServiceImpl<ZbTypeMapper, ZbType>
        implements ZbTypeService {

    @Override
    public List<ZbType> buildTree(List<ZbType> zbTypeList) {
        List<ZbType> returnList = new ArrayList<ZbType>();
        List<ZbType> parentList = zbTypeList.stream().filter(e -> StringUtils.isBlank(e.getParentId())).collect(Collectors.toList());
        for (ZbType zbType : parentList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            recursionFn(zbTypeList, zbType);
            returnList.add(zbType);
        }
        if (returnList.isEmpty()) {
            returnList = zbTypeList;
        }
        return returnList;
    }

    private void recursionFn(List<ZbType> list, ZbType t) {
        // 得到子节点列表
        List<ZbType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (ZbType tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ZbType> getChildList(List<ZbType> list, ZbType t) {
        List<ZbType> tlist = new ArrayList<ZbType>();
        Iterator<ZbType> it = list.iterator();
        while (it.hasNext()) {
            ZbType n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ZbType> list, ZbType t) {
        return getChildList(list, t).size() > 0;
    }
}




